import React, { Component } from 'react';
import { marked } from 'marked';
import hljs from 'highlight.js';
import { Button } from 'antd';
import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons';
import { CSSTransition } from 'react-transition-group';
import './style.less';

export interface MarkdownState {
  content: string;
  isShowDisplay: boolean;
}
export interface MarkdownProps {
  content: string;
}

class Markdown extends Component<MarkdownProps, MarkdownState> {
  private editor!: React.RefObject<HTMLTextAreaElement>;
  private display!: React.RefObject<HTMLDivElement>;
  constructor(props: MarkdownProps) {
    super(props);
    this.state = {
      content: '',
      isShowDisplay: true,
    };
    this.editor = React.createRef();
    this.display = React.createRef();
    this.init();
  }

  init() {
    if (!this.props.content) return;
    this.setState({
      content: this.props.content,
    });
  }

  editorChange() {
    marked.setOptions({
      renderer: new marked.Renderer(),
      highlight: function (code, lang) {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        return hljs.highlight(code, { language }).value;
      },
      langPrefix: 'hljs language-', // highlight.js css expects a top-level 'hljs' class.
      pedantic: false,
      gfm: true,
      breaks: false,
      sanitize: false,
      smartLists: true,
      smartypants: false,
      xhtml: false,
    });
    if (this.display.current && this.editor.current) {
      this.display.current.innerHTML = marked(this.editor.current.value);
    }
  }

  switchDisplay() {
    this.setState({
      isShowDisplay: !this.state.isShowDisplay,
    });
    setTimeout(() => {
      console.log(this.state.isShowDisplay);
    }, 1000);
  }

  render() {
    return (
      <div id="markdown">
        <section className="editor">
          <textarea
            onChange={this.editorChange.bind(this)}
            ref={this.editor}
          ></textarea>
        </section>
        <Button
          size="middle"
          onClick={this.switchDisplay.bind(this)}
          icon={
            !this.state.isShowDisplay ? (
              <CaretLeftOutlined />
            ) : (
              <CaretRightOutlined />
            )
          }
        ></Button>
        <CSSTransition
          unmountOnExit
          classNames="fade"
          in={this.state.isShowDisplay}
          timeout={500}
        >
          <section ref={this.display} className="show"></section>
        </CSSTransition>
      </div>
    );
  }
}
export default Markdown;
